<script setup lang="ts">
import {useRoute} from "vue-router";
import {getBlogByUid} from "@/api/post/post";
import {computed, onBeforeMount, ref, onMounted, onBeforeUnmount} from "vue";
import {commonConsoleLog, ECode, iconFontAddress, setPostMetaInfo} from "@/util/commonUtil";
import _ from "lodash";
import PostHeader from "@/components/post/header/index.vue"
import PostLayout from "@/components/post/layout/index.vue"
import {useAppConfigStore} from "@/store/system/appConfigStore";
import Comment from "@/components/comment/index.vue"
import AsideAuthor from "@/components/post/aside/author/index.vue"
import BottomPraise from "@/components/bottomPraise/index.vue"
import {createFromIconfontCN} from "@ant-design/icons-vue";
import ShareBottom from "@/components/share/index.vue";
import LeftNavigation from "@/components/post/aside/leftNavigation/index.vue"
import {v4 as uuidV4} from 'uuid';
import {recorderBehavior} from "@/api/system/system";

const route = useRoute();
const blogData = ref<any>({
  tagList: [],
  photoList: [],
  blogSort: {},
  subject: {},
  subjectItemList: [],
  content: "",
  user: {},
  praiseInfo: {},
  collectInfo: {},
  praiseUserList: [],
  visitAuthExtraVo: {}
})
const blogUid = ref<any>('')
const blogOid = ref<any>(null)
const subjectUid = ref<any>(null)
const commentInfo = ref<any>({
  source: "BLOG_INFO",
  maxReplyLevel: 4, // 最大回复深度
  blogUid: route.query.blogUid,
})
// 专题列表信息
const subjectItemList = ref<any>([])
// 专题信息
const subject = ref<any>({})
const isCopy = ref<number>(0)
const openComment = computed(() => useAppConfigStore().openComment)
const componentShowMap = computed(() => useAppConfigStore().componentShowMap)
const preArticle = ref<any>({})
const shareShow = ref<any>('')
// 引入阿里图标库
const IconFont = createFromIconfontCN({
  scriptUrl: iconFontAddress,
});
onBeforeMount(async () => {
  await getPostInfo()
  prevArticle()
})
// 页面加载时滚动到顶部
onMounted(() => {
  window.scrollTo(0, 0);
});
onBeforeUnmount(()=>{
  document.title = computed(()=>useAppConfigStore().title).value
})
/**
 * ===================================================
 */
function postInit() {
  let oid = route.params.blogOid
  subjectUid.value = route.query.subject;
  // 根据类型判断是否是oid还是uid
  if (oid.length === 32) {
    blogUid.value = oid;
  } else {
    blogOid.value = oid;
  }
}

async function getPostInfo() {
  postInit()
  let params = new URLSearchParams();
  if (!_.isNull(blogOid.value)) {
    params.append("oid", blogOid.value);
  } else {
    params.append("uid", blogUid.value);
  }
  if (!_.isUndefined(subjectUid.value) && !_.isNull(subjectUid.value)) {
    params.append("subjectUid", subjectUid.value);
  }
  // 开启图片懒加载
  params.append("isLazy", "1");
  await getBlogByUid(params).then((response: any) => {
    if (response.code == ECode.SUCCESS) {
      let responseBlogData = response.data;
      // 设置meta信息
      setPostMetaInfo(responseBlogData.title, responseBlogData.summary, responseBlogData.summary)
      blogUid.value = response.data.uid;
      commentInfo.value.blogUid = response.data.uid;
      blogOid.value = response.data.oid;
      subjectItemList.value = response.data.subjectItemList;
      subject.value = response.data.subject;
      isCopy.value = response.data.isCopy;
      blogData.value = responseBlogData;
      // 5S后埋点信息上报
      setTimeout(() => {
        recorderBehavior({
          "otherData": blogData.value.title,
          "bizUid": blogData.value.uid,
          "bizType": "BLOG",
          "behavior": "BLOG_CONTNET",
        }).then((response: any) => {
          if (response.code == ECode.SUCCESS) {
            commonConsoleLog("文章信息上报成功")
          }
        })
      }, 5000);
    }
  })
}

function getSubjectIndex() {
  let bUid = blogUid.value;
  let index = -1;
  let subjectList = subjectItemList.value;
  if (!subjectList || _.isEmpty(subjectList)) {
    return;
  }
  for (let a = 0; a < subjectList.length; a++) {
    // 判断当前文章所出的专栏位置
    if (subjectList[a].blogUid == bUid) {
      index = a;
    }
  }
  return index;
}

function prevArticle() {
  let index: any = getSubjectIndex();
  if (_.isNaN(subjectItemList.value[index - 1].blog)) {
    return;
  }
  if (index <= 0 || !subjectItemList.value[index - 1].blog) {
    return;
  }
  preArticle.value = subjectItemList.value[index - 1].blog;
}

function shareShowClick() {
  // 产生随机数，使弹框弹出
  shareShow.value = uuidV4();
}

</script>

<template>
  <div class="postInfoMain">
    <!-- 文章头部展示 -->
    <div class="articleHeader">
      <PostHeader :post-data="blogData" :resource-type="'1'"/>
    </div>
    <!-- 左侧边栏 -->
    <LeftNavigation
        :bizUid="blogData.uid"
        :resourceType="'1'"
        :isCollectValue="blogData.collectInfo.isCollect"
        :collectCountValue="blogData.collectInfo.collectCount"
        :isPraiseValue="blogData.praiseInfo.isPraise"
        :praiseCountValue="blogData.praiseInfo.praiseCount"
        :isTreadValue="blogData.praiseInfo.isTread"
        :treadCountValue="blogData.praiseInfo.treadCount"
    />
    <!-- 文章信息展示 -->
    <div class="articleContent m-auto mb-4">
      <PostLayout :post-data="blogData"
                  :preArticle="preArticle"
                  :commentInfo="commentInfo"
                  :openComment="openComment"/>
      <a-divider>
        <span class="text-gray-300">文章完</span>
      </a-divider>
      <div class="articlePraise">
        <BottomPraise :resource-uid="blogUid" resource-type="1" v-if="componentShowMap.showUserPrise"/>
      </div>
      <a-divider></a-divider>
    </div>
    <!-- 文章底部作者信息与评论 -->
    <aside class="commentArea grid z-[2] m-auto" id="commentArea">
      <AsideAuthor :user-info="blogData.user"
                   :preArticle="preArticle"
                   :copyright="blogData.copyright"/>
      <comment v-if="openComment == '1'"
               :maxReplyLevel="commentInfo.maxReplyLevel"
               :targetId="commentInfo.blogUid"
               :author-uid="blogData.userUid"
               :tableName="commentInfo.source"
               :show-comment-box="true"
               :show-cancel="false">
        <div data-fancybox data-src="#commentBox" class="cursor-pointer text-orange-500">
          <IconFont type="icon-pinglun" class="text-base mr-1"/>
          <span>发表评论</span>
        </div>
      </comment>
    </aside>
    <!-- 侧边分享按钮 -->
    <a-float-button :style="{ bottom: '6.5rem' }" @click="shareShowClick">
      <template #icon>
        <IconFont type="icon-fenxiang"/>
      </template>
    </a-float-button>
    <!-- 侧边分享弹窗 -->
    <ShareBottom :shareShow="shareShow"/>
  </div>
</template>

<style scoped lang="less">
.postInfoMain {
  padding-block: var(--edge-lr) calc(var(--radius) + var(--edge-lr));
  padding-block-start: 0;
  margin: auto auto calc(var(--radius) * -1);
}

.articleContent, .commentArea {
  max-width: min(1000px, 100%);
}

.commentArea {
  width: min(var(--content-size), 100%);
  gap: var(--gap-area);
  margin-inline: auto;
}

.shareBottom {
  background: var(--bg);
  border-radius: 50%;
}

:deep(.ant-float-btn-icon) {
  width: auto !important;
}
</style>
